package com.longcai.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.longcai.entity.homegood.ClyjGoodsHomepage;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;


public class SolrConnect {
    // private static String url = "http://localhost:8080/solr";
    // private static String url ="http://10.246.145.3:8983/solr";
    private static String solrUrl = "http://1.62.100.7:8983/solr/goods_core";
    private static String count = "10000";

    public static boolean insertSolr(List<ClyjGoodsHomepage> list) {
        boolean flag = false;
        try {
            Builder url = new Builder(solrUrl);
            HttpSolrClient currentServer = url.build();
            Collection<SolrInputDocument> docs = new LinkedList<SolrInputDocument>();
            int j = 0;
            for (int i = 0; i < list.size(); i++) {
                j += 1;
                ClyjGoodsHomepage viewObject = list.get(i);
                SolrInputDocument solrDoc = new SolrInputDocument();
                solrDoc.addField("goodsId", viewObject.getGoodsId() == null ? " " : viewObject.getGoodsId());
                solrDoc.addField("goodsTypeId", viewObject.getGoodsTypeId() == null ? " " : viewObject.getGoodsTypeId());
                solrDoc.addField("goodsName", viewObject.getGoodsName() == null ? " " : viewObject.getGoodsName());
                solrDoc.addField("originalPrice", viewObject.getOriginalPrice().toString() == null ? " " : viewObject.getOriginalPrice().toString());
                solrDoc.addField("presentPrice", viewObject.getPresentPrice().toString() == null ? " " : viewObject.getPresentPrice().toString());
                solrDoc.addField("goodsStock", viewObject.getGoodsStock() == null ? " " : viewObject.getGoodsStock());
                solrDoc.addField("postFee", viewObject.getPostFee().toString() == null ? " " : viewObject.getPostFee().toString());
                solrDoc.addField("monthSales", viewObject.getMonthSales() == null ? "" : viewObject.getMonthSales());
                solrDoc.addField("goodsSpec", viewObject.getGoodsSpec() == null ? "" : viewObject.getGoodsSpec());
                solrDoc.addField("pocketMoney", viewObject.getPocketMoney().toString() == null ? "" : viewObject.getPocketMoney().toString());
                solrDoc.addField("goodsDepict", viewObject.getGoodsDepict() == null ? " " : viewObject.getGoodsDepict());
                solrDoc.addField("goodsDetail", viewObject.getGoodsDetail() == null ? " " : viewObject.getGoodsDetail());
                solrDoc.addField("goodsStatus", viewObject.getGoodsStatus() == null ? " " : viewObject.getGoodsStatus());
                solrDoc.addField("createTime", viewObject.getCreateTime() == null ? " " : viewObject.getCreateTime());
                solrDoc.addField("updateTime", viewObject.getUpdateTime() == null ? " " : viewObject.getUpdateTime());
                solrDoc.addField("goodsBanner", viewObject.getGoodsBanner() == null ? " " : viewObject.getGoodsBanner());
                solrDoc.addField("goodsBrandId", viewObject.getGoodsBrandId() == null ? " " : viewObject.getGoodsBrandId());
                solrDoc.addField("goodsPic", viewObject.getGoodsPic() == null ? " " : viewObject.getGoodsPic());
                solrDoc.addField("delFlag", viewObject.getDelFlag() == null ? " " : viewObject.getDelFlag());
                docs.add(solrDoc);
                try {
                    if ((j % Integer.parseInt(count) == 0) && docs.size() > 0) {
                        currentServer.add(docs);
                        currentServer.commit();
                        currentServer.optimize();

                        System.out.println("已经成功导入 " + docs.size()
                                + " 条数据" + new Date() + "j=" + j);
                        docs.clear();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

            if (docs.size() > 0) {
                try {
                    currentServer.add(docs);
                    currentServer.commit();
                    currentServer.optimize();
                    System.out
                            .println("已经成功导入 " + docs.size()
                                    + " 条数据      " + new Date()
                                    + "   j=" + j);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
        return flag;
    }


    public static Page<ClyjGoodsHomepage> getAll(String value, Page<ClyjGoodsHomepage> page) {
        int pageNo = page.getPageNo();
        int pageSize = page.getPageSize();
        page.setPageSize(pageSize);
        Builder url = new Builder(solrUrl);
        HttpSolrClient currentServer = url.build();
        SolrQuery query = new SolrQuery(transformSolrMetacharactor(value).replace("\\", ""));
        //  int start =0;
        query.setStart(pageNo * 20);
        query.setRows(pageSize);
        System.out.println(pageNo + "----------" + pageSize);
        //query.setFilterQueries("nachn" + value);
        QueryResponse response = null;
        List<ClyjGoodsHomepage> lpojo = new ArrayList<ClyjGoodsHomepage>();
        try {
            response = currentServer.query(query);
            SolrDocumentList list = response.getResults();
            System.out.println(list.size() + "=list长度");
            page.setTotalCount(list.size());
            SolrDocumentList results = response.getResults();
            for (SolrDocument solrDocument : results) {
                ClyjGoodsHomepage c = new ClyjGoodsHomepage();
                List<String> goodsId = (List<String>) solrDocument.get("goodsId");
                List<String> goodsType = (List<String>) solrDocument.get("goodsTypeId");
                List<String> goodsName = (List<String>) solrDocument.get("goodsName");
                List<String> originalPrice = (List<String>) solrDocument.get("originalPrice");
                List<String> presentPrice = (List<String>) solrDocument.get("presentPrice");
                List<String> goodsStock = (List<String>) solrDocument.get("goodsStock");
                List<String> postFee = (List<String>) solrDocument.get("postFee");
                List<String> monthSales = (List<String>) solrDocument.get("monthSales");
                List<String> goodsSpec = (List<String>) solrDocument.get("goodsSpec");
                List<String> pocketMoney = (List<String>) solrDocument.get("pocketMoney");
                List<String> goodsDepict = (List<String>) solrDocument.get("goodsDepict");
                List<String> goodsDetail = (List<String>) solrDocument.get("goodsDetail");
                List<String> goodsStatus = (List<String>) solrDocument.get("goodsStatus");
                List<String> createTime = (List<String>) solrDocument.get("createTime");
                List<String> updateTime = (List<String>) solrDocument.get("updateTime");
                List<String> goodsBanner = (List<String>) solrDocument.get("goodsBanner");
                List<String> goodsBrandId = (List<String>) solrDocument.get("goodsBrandId");
                List<String> goodsPic = (List<String>) solrDocument.get("goodsPic");
                List<String> delFlag = (List<String>) solrDocument.get("delFlag");
                SimpleDateFormat sdf1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
                //SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                c.setGoodsId(goodsId.size() == 0 ? "" : String.valueOf(goodsId.get(0)));
                c.setGoodsTypeId(goodsType.size() == 0 ? "" : String.valueOf(goodsType.get(0)));
                c.setGoodsName(goodsName.size() == 0 ? "" : String.valueOf(goodsName.get(0)));
                c.setOriginalPrice(originalPrice.size() == 0 ? BigDecimal.ZERO : new BigDecimal(originalPrice.get(0)));
                c.setPresentPrice(presentPrice.size() == 0 ? BigDecimal.ZERO : new BigDecimal(presentPrice.get(0)));
                c.setGoodsStock(goodsStock.size() == 0 ? 0 : Integer.valueOf(String.valueOf(goodsStock.get(0))));
                c.setPostFee(postFee.size() == 0 ? BigDecimal.ZERO : new BigDecimal(postFee.get(0)));
                c.setMonthSales(monthSales.size() == 0 ? 0 : Integer.valueOf(String.valueOf(monthSales.get(0))));
                c.setGoodsSpec(goodsSpec.size() == 0 ? "" : String.valueOf(goodsSpec.get(0)));
                c.setPocketMoney(pocketMoney.size() == 0 ? BigDecimal.ZERO : new BigDecimal(pocketMoney.get(0)));
                c.setGoodsDepict(goodsDepict.size() == 0 ? "" : String.valueOf(goodsDepict.get(0)));
                c.setGoodsDetail(goodsDetail.size() == 0 ? "" : String.valueOf(goodsDetail.get(0)));
                c.setGoodsStatus(goodsStatus.size() == 0 ? 0 : Integer.valueOf(String.valueOf(goodsStatus.get(0))));
                c.setCreateTime(createTime.size() == 0 ? new Date() : sdf1.parse(createTime.get(0)));
                c.setUpdateTime(updateTime.size() == 0 ? new Date() : sdf1.parse(updateTime.get(0)));
                c.setGoodsBanner(goodsBanner.size() == 0 ? "" : String.valueOf(goodsBanner.get(0)));
                c.setGoodsBrandId(goodsBrandId.size() == 0 ? "" : String.valueOf(goodsBrandId.get(0)));
                c.setGoodsPic(goodsPic.size() == 0 ? "" : String.valueOf(goodsPic.get(0)));
                c.setDelFlag(delFlag.size() == 0 ? "" : String.valueOf(delFlag.get(0)));
                lpojo.add(c);
            }
            page.setResult(lpojo);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }


    public static ClyjGoodsHomepage queryById(String id) {
        Builder url = new Builder(solrUrl);
        HttpSolrClient currentServer = url.build();
        SolrQuery query = new SolrQuery("id:" + id);
        QueryResponse response = null;
        try {
            response = currentServer.query(query);
            SolrDocumentList list = response.getResults();
            for (int i = 0; i < list.size(); i++) {
                SolrDocument doc = list.get(i);
            }
            List<ClyjGoodsHomepage> list1 = response.getBeans(ClyjGoodsHomepage.class);
            if (list1 == null || list1.size() == 0) {
                return new ClyjGoodsHomepage();
            } else {
                return list1.get(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ClyjGoodsHomepage();
    }

    public static void deleById(String id) {
        Builder url = new Builder(solrUrl);
        HttpSolrClient currentServer = url.build();
        try {
            currentServer.deleteById(id);
            currentServer.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String transformSolrMetacharactor(String input) {
        if (input == null) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            String regex = "[+\\-&|!(){}\\[\\]^\"~*?:(\\)]";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(input);
            while (matcher.find()) {
                matcher.appendReplacement(sb, "\\\\" + matcher.group());
            }
            matcher.appendTail(sb);
            return sb.toString();
        }
    }

    public static String index(String v, String[] arry) {
        if (v == null || "".equals(v)) {
            return v;
        }
        StringBuffer sb = new StringBuffer(v);
        boolean flag = false;
        for (int i = 0; i < arry.length; i++) {
            if (sb.indexOf(arry[i]) != -1) {
                String s = sb.substring(sb.indexOf(arry[i]), sb
                        .indexOf(arry[i])
                        + arry[i].length());
                sb.replace(sb.indexOf(arry[i]), sb.indexOf(arry[i])
                        + arry[i].length(), "<font color=red>" + s + "</font>");
                flag = true;
            }
        }
        // System.out.println(sb.toString());
        if (flag == true) {
            return sb.toString();
        } else {
            return v;
        }
    }

    public static void deleteAllIndex() throws SolrServerException,
            IOException {
        Builder url = new Builder(solrUrl);
        HttpSolrClient currentServer = url.build();
        currentServer.deleteByQuery("*:*");
        currentServer.commit();
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = pattern.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    //    public  void getBySql(String username,Map<String,String> sqlMap,T_TableService t_TableService) throws SolrServerException, Exception{
//    	   SolrDao SolrDao=new SolrDaoImpl(username);
//    	 // DBHelp<ViewObject> dBHelp = new DBHelp<ViewObject>(username);
//    	if (sqlMap != null){
//        	List<ViewObject> list = new ArrayList<ViewObject>();
//        	T_Table table =null;
//        	Set<String> keySet = sqlMap.keySet();
//        	for(String tableName : keySet){
//        		List<ViewObject> list1 = SolrDao.getG0ZXCP(sqlMap.get(tableName), tableName);
//        		list.addAll(list1);
//        		 table = t_TableService.getTableByTableName(tableName);
//        		 if (table != null){
//        		 for (ViewObject vo : list1) {
//        			 vo.setLogical_table_name(table.getLogical_table_name());
//        			vo.setComment(table.getComment());
//        			vo.setFieldName(table.getFiledtxt());
//        		}}
//        	}
//        	System.out.println(list.size());
//        	if (list.size()>0 ){
//        		try {
//            		SolrConnect.deleteAllIndex();
//            	} catch (SolrServerException e) {
//            		e.printStackTrace();
//            	} catch (IOException e) {
//            		e.printStackTrace();
//            	}
//            	SolrConnect.insertSolr(list);
//        	}
//        
//        
//    	}
//    }
    public static void main(String[] args) throws SolrServerException,
            IOException {
        SolrConnect s = new SolrConnect();
       /* List<ClyjGoodsHomepage> list = new ArrayList<ClyjGoodsHomepage>();
        for (int i = 6; i <= 10; i++) {
            ClyjGoodsHomepage c = new ClyjGoodsHomepage();
            c.setGoodsId(i);
            c.setGoodsName("商品1" + String.valueOf(i) + "商品ABCDDDD商品");
            list.add(c);
        }
        s.insertSolr(list);*/
//    	Page<ClyjSeckillGoods> page = new Page<ClyjSeckillGoods>();
//
//    	        page.setPageNo(Integer.valueOf(0));
//    	            page = getAll("id:2 AND goodsName:*2*", page);
//    	            System.out.println(page.getResult().size());
//    	            for (ClyjSeckillGoods ss : page.getResult()) {
//
//    	               System.out.println(ss.getId()+"-"+ss.getGoodsName());
//    	            }
//    	            System.out.println("=================================");
        s.deleteAllIndex();
    }
}